<template>
    <div class="white-box">
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">运单/订单：</span>
                <el-input
                    placeholder="请输入运单/订单号"
                    v-model="state.code"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">运单状态：</span>
                <el-select
                    v-model="state.wayBillState"
                    placeholder="请选择运单状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.waybillStateList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">所属线路：</span>
                <SelectLoadMore
                    v-model:selectValue="state.lineSid"
                    v-model:options="state.lineOptions"
                    value="sid"
                    label="lineName"
                    popperClass="line"
                    placeholder="请选择线路"
                    :apiFun="getLineOptions"
                />
            </div>
            <div class="task-one__item">
                <span class="task-one__label">运单车辆：</span>
                <SelectLoadMore
                    v-model:selectValue="state.carSid"
                    v-model:options="state.carOptions"
                    value="sid"
                    label="carNumber"
                    popperClass="car"
                    placeholder="请选择车辆"
                    :apiFun="getCarOptions"
                />
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:waybill:delete']"
                @click="onClickDel()"
                >批量删除运单</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @sort-change="sortChange"
        >
            <el-table-column
                type="selection"
                width="55"
                v-hasPermi="['enttp:waybill:delete']"
                :selectable="(row) => row.wayBillState === 1"
            />
            <el-table-column
                prop="orderCode"
                label="订单流水号"
                min-width="200"
                fixed="left"
            ></el-table-column>
            <el-table-column
                prop="wayBillCode"
                label="运单流水号"
                min-width="200"
            >
            </el-table-column>
            <el-table-column
                prop="wayBillState"
                label="运单状态"
                min-width="160"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "waybill_state",
                            row.wayBillState
                        )
                    }}
                </template>
            </el-table-column>
            <!-- <el-table-column
                prop="tripsId"
                label="车次ID"
                min-width="200"
                sortable="custom"
            >
            </el-table-column> -->
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            />
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            //  {
                            //     props: {
                            //         onClick: () =>
                            //             onClickPrintLabel(row.wayBillCode),
                            //         'v-hasPermi': ['enttp:labelDesign:list'],
                            //     },
                            //     text: '打印',
                            // },
                            {
                                props: {
                                    onClick: () =>
                                        onClickConfirmArrive(row.sid),
                                    'v-hasPermi': [
                                        'enttp:waybill:systemArriveAtDestination',
                                    ],
                                },
                                text: '确认到达',
                                isRender: row.carrier,
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:waybill:delete'],
                                },
                                text: '删除',
                                isRender: row.wayBillState === 1,
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>
</template>

<script setup>
import { inject, reactive, onMounted, onActivated } from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import SelectLoadMore from "@/components/selectLoadMore.vue";
import { getLines } from "@/apis/enterprise/line.js";
import { getCars } from "@/apis/enterprise/car.js";
import { getOrders } from "@/apis/order/order.js";
import {
    getWaybills,
    delOrderWaybill,
    confirmArrive,
} from "@/apis/order/waybill.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore
    .getDictMembers("waybill_state")
    .then((res) => (state.waybillStateList = res));

const router = useRouter();
const $message = inject("$message");

const state = reactive({
    waybillStateList: [],
    lineOptions: [], // 线路列表
    carOptions: [], // 车辆列表
    orderOptions: [], // 订单列表
    ascended: false,
    sortFieldName: null,
    carrier: null,
    carSid: null,
    lineSid: null,
    status: null,
    code: null,
    wayBillState: null,
    sidList: [],
});

onActivated(() => {
    pubParams(getList);
});

const getLineOptions = async (params) => {
    const res = await getLines({
        ...params,
        lineName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getCarOptions = async (params) => {
    const res = await getCars({
        ...params,
        carNumber: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getOrderOptions = async (params) => {
    const res = await getOrders({
        ...params,
        orderCode: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getWaybills({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            carrier: state.carrier,
            carSid: state.carSid,
            lineSid: state.lineSid,
            status: state.status,
            code: state.code,
            wayBillState: state.wayBillState,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除运单吗？");
    const res = await delOrderWaybill({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 确认到达终点
const onClickConfirmArrive = async (sid) => {
    await ElMessageBox.confirm("确定运单到达终点吗？");
    const res = await confirmArrive({ sid });
    if (res.data.code == 200) {
        $message({ message: "操作成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};
</script>

<style lang="less" scoped></style>
